import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "dalian_dlsrmzf"

    province: str = "辽宁省"  # 取表格
    city: str = "大连市"  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "大连市人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.dl.gov.cn/col/col483/index.html?vc_xxgkarea=2102000056-1&jh=261"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = "https://www.dl.gov.cn/module/xxgk/xxgk_rulebase_search.jsp?q=&xxgkjd=2102000056-1&type=0&currpage=1"
        params = {}
        headers = {}
        # 将参数转换为 URL 编码的字符串
        encoded_params = urllib.parse.urlencode(params)
        # 发送 POST 请求
        yield scrapy.Request(
            url=url,
            method='POST',
            body=encoded_params,
            headers=headers,
            callback=self.detail_requests
        )

    def detail_requests(self, response, **kwargs):
        links = response.xpath('//a[@class="zc_list_tit"]/@href').getall()
        pages = int(response.xpath('//span[@id="totalpages"]/text()').get())
        for link in links:
            yield response.follow(link, callback=self.parse_detail)

        if response.meta.get("is_next") is not False:
            for page in range(2, pages + 1):
                print("当前页：", page)
                url = f"https://www.dl.gov.cn/module/xxgk/xxgk_rulebase_search.jsp?q=&xxgkjd=2102000056-1&type=0&currpage={page}"
                params = {}
                headers = {}
                # 将参数转换为 URL 编码的字符串
                encoded_params = urllib.parse.urlencode(params)
                # 发送 POST 请求
                yield scrapy.Request(
                    url=url,
                    method='POST',
                    body=encoded_params,
                    headers=headers,
                    callback=self.detail_requests,
                    meta={'is_next': False}
                )

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['source_url'] = response.url
        p_pattern = r"\d{4}年\d{1,2}月\d{1,2}日"
        item['publish_date'] = re.search(p_pattern, response.xpath("""string(//div[@class='time']/p[1])""").get()).group()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl dalian_dlsrmzf".split())
